package com.hua.dao.test37;

import com.hua.entitiy.test37.T_User;
import com.hua.util.JDBCConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/11/17.
 */
public class RegistDao {
    private JDBCConnection jdbc;

    public boolean regist(T_User tUser){
        jdbc=new JDBCConnection();
        Connection conn=jdbc.getConnection();
        String sql="insert into t_user values (?,?,?,?,?,?)";
        try{
            PreparedStatement ps=conn.prepareStatement(sql);
            String id=UUID.randomUUID().toString().replace("-","");
            ps.setString(1, id);
            ps.setString(2,tUser.getUserName());
            ps.setString(3,tUser.getUserPwd());
            ps.setString(4,String.valueOf(tUser.getGender()));
            ps.setString(5,tUser.getEmail());
            ps.setString(6,tUser.getExplain());
            if(!ps.execute()){
                jdbc.close();
                conn=jdbc.getConnection();
                List<String> likes=tUser.getLikes();
                String sql2="insert into t_user_like values(?,?,?)";
                ps=conn.prepareStatement(sql2);
                for(String str:likes){
                    ps.setString(1,UUID.randomUUID().toString().replace("-",""));
                    ps.setString(2,id);
                    ps.setString(3,str);
                    ps.addBatch();
                }
                int [] is=ps.executeBatch();
                System.out.println(is);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            jdbc.close();
        }

        return true;
    }


    public boolean valiUserName(String userName){
        jdbc=new JDBCConnection();
        Connection conn=jdbc.getConnection();
        String sql="select id from t_user where username=?";
        try{
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,userName);
            ResultSet rs=ps.executeQuery();
            if(rs.next()){
                return false;
            }
        }catch(SQLException e){
            e.printStackTrace();
        }finally {
            jdbc.close();
        }
        return true;
    }
}
